package nl.justobjects.pushlet.core;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import nl.justobjects.pushlet.util.Log;

public class JSONAdapter implements ClientAdapter {

    private PrintWriter out = null;
	private HttpServletResponse servletRsp;
	private int seq = 0;
	
	public JSONAdapter(HttpServletResponse aServletResponse) {
		servletRsp = aServletResponse;
	}

	@Override
	public void start() throws IOException {
        servletRsp.setContentType("application/json;charset=UTF-8");
		out = servletRsp.getWriter();
		servletRsp = null;
		out.print("[");
	}

	@Override
	public void push(Event anEvent) throws IOException {
		// debug("event=" + anEvent);
		if (seq > 0)
			out.print(",");
        else
            seq++;
		out.print(anEvent.isUnmodifable() ? anEvent.getJSONString() : anEvent.toJSON());
		// out.flush();
	}

	@Override
	public void stop() throws IOException {
		out.print("]");
		out.flush();
	}
	
	private void debug(String s) {
		Log.debug("[JSONAdapter]" + s);
	}

}
